package com.atsmart.app.activity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import com.atsmart.app.BizApp;
import com.atsmart.app.R;
import com.atsmart.app.adapter.LoadingAdapter;
import com.atsmart.app.adapter.TaskListAdapter;
import com.atsmart.app.exception.BizException;
import com.atsmart.app.model.NumberResponseInfo;
import com.atsmart.app.model.PageInfo;
import com.atsmart.app.model.TaskInfo;
import com.atsmart.app.model.TaskListInfo;
import com.atsmart.app.sql.NumberSqlHelper;
import com.atsmart.app.sql.TaskInfoSqlHelper;
import com.atsmart.app.sql.TaskNumSqlHelper;
import com.atsmart.app.utils.DialogUtil;
import com.atsmart.app.utils.IntentUtil;
import com.atsmart.app.utils.PersistentKeyUtil;
import com.atsmart.app.utils.PrefsUtils;
import com.atsmart.app.utils.StringUtil;
import com.atsmart.app.webservice.ServiceAsynTask;
import com.atsmart.app.webservice.ServiceHelper;
import com.atsmart.app.webservice.ServiceHost;
import com.google.json.Gson;
import com.google.json.JsonParseException;

public class TaskListActivity extends BaseActivity implements
		LoadingAdapter.Delegate, LoadingAdapter.OnLoadingRowShowingHandler,
		OnClickListener {
	private static final String TAG = TaskListActivity.class.getName();
	public static final int TASK_TYPE_LIST = 1;
	public static final int TASK_TYPE_DONE = 2;
	public static final int TASK_TYPE_OVERDUE = 3;
	private ListView listView;
	private static TaskListInfo datasource;
	private TaskListAdapter adapter;
	private static final int pageSize = 20;
	private boolean isNeedLoading = false;
	private int totalRow;
	private int pageIndex = 0;
	private int taskType;
	private Button refresh;
	private Button history;
	private TaskInfoSqlHelper tsql = null;
	private static boolean asyntaskIsFinished = true;
	private NumberSqlHelper nsql = null;
	private TaskNumSqlHelper tnsql = null;
 
	private int isPage = 0;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.task_list_layout);
//		context = this;
		 
		BizApp.getInstance().setExited(false);
		refresh = (Button) findViewById(R.id.btn_refresh);
		history = (Button) findViewById(R.id.btn_history);
		history.setBackgroundResource(R.drawable.btn_retake_press);
		history.setVisibility(View.INVISIBLE);
		refresh.setOnClickListener(this);
		history.setOnClickListener(this);
		tsql = new TaskInfoSqlHelper();
		tsql.open(BizApp.getInstance().getSqlHelper());
		tnsql = new TaskNumSqlHelper();
		tnsql.open(BizApp.getInstance().getSqlHelper());
		taskType = getIntent().getIntExtra(TaskForAllActivity.TASK_TYPE, 1);
		listView = (ListView) findViewById(R.id.listview);
		nsql = new NumberSqlHelper();
		nsql.open(BizApp.getInstance().getSqlHelper());
		nsql.deleteAttributeByType(1);
		NumberResponseInfo at = new NumberResponseInfo();
		at.setLastTime(Calendar.getInstance().getTimeInMillis());
		at.setType(1);
		nsql.addNumberInfo(at);
		BizApp.getInstance().showMemory();
		
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if (taskType == TASK_TYPE_DONE) {
					return;
				}
				if (adapter == null) {
					return;
				}
				TaskInfo taskInfo = (TaskInfo) adapter.getItem(position);
				if (taskInfo == null) {
					return;
				}
				Bundle bundle = new Bundle();
				bundle.putInt(PersistentKeyUtil.REPORT_TYPE, 1);
				bundle.putString(PersistentKeyUtil.TEMPLATE_NAME,
						taskInfo.getName());
				bundle.putInt(PersistentKeyUtil.TASK_ID, taskInfo.getId());
				bundle.putString(PersistentKeyUtil.TASK_TIME,
						taskInfo.getDate());
				bundle.putString(PersistentKeyUtil.TASK_NAME,
						taskInfo.getName());
				IntentUtil.redirectToNext(TaskListActivity.this,
						ReportListActivity.class, bundle);
			}
		});
	}

	@Override
	protected void onResume() {
		super.onResume();
		nsql = new NumberSqlHelper();
		nsql.open(BizApp.getInstance().getSqlHelper());
		nsql.deleteAttributeByType(1);
		NumberResponseInfo at = new NumberResponseInfo();
		at.setLastTime(Calendar.getInstance().getTimeInMillis());
		at.setType(1);
		nsql.addNumberInfo(at);

		count = tsql.getTaskListCount();
		if (count > 0) {
			if (asyntaskIsFinished) {
				showLoading();
				pageIndex = 0;
				isFromSql = true;
				getDataFromSql();
				asyntaskIsFinished = false;
			}
		} else {
			if ((BizApp.getInstance().isNetworkAvailable() || BizApp.getInstance().isWiFiActive()) && BizApp.getInstance().keeping) {
				isFromSql = false;
				if (asyntaskIsFinished) {
					showLoading();
					pageIndex = 0;
					getData();
					asyntaskIsFinished = false;
				}
			}
		}

	}
	
	private boolean isFromSql = false;
	private int count;
	private void getDataFromSql(){
//		 Log.e("TAG", "get data from sql countA: = " + count);
		registerLoadStatus(TAG);
		new ServiceAsynTask<TaskListInfo>() {

			@Override
			protected TaskListInfo callService() throws IOException,
					JsonParseException, AssertionError, BizException,Exception {
				PageInfo pageInfo = new PageInfo();
				pageInfo.begin = pageIndex * pageSize;
				pageInfo.end = (pageIndex + 1) * pageSize;
				if(pageInfo.end >= count){
					pageInfo.end = count;
				}
//				Log.e("TAG", "tag: = " + pageSize + " , " + pageIndex);
				return tsql.getTaskList(pageInfo.begin, pageInfo.end);

			}

			@Override
			protected void runWithResult(TaskListInfo result) throws Exception {
				if (result != null && result.getTasks() != null) {
					datasource = result;
					bindData();
				}else{
					 
				}
				asyntaskIsFinished = true;
				hideLoading();
				finishedLoad(TAG);
			}

			@Override
			protected void runWithError(TaskListInfo result, int iErrorCode)
					throws Exception {
				try{
					tsql.delete();
				}catch (Exception e) {
				}
				
				 
				asyntaskIsFinished = true;
				finishedLoad(TAG);
				hideLoading();
			}
		}.execute();
	}

	private void getData() {
		registerLoadStatus(TAG);
		new ServiceAsynTask<TaskListInfo>() {

			@Override
			protected TaskListInfo callService() throws IOException,
					JsonParseException, AssertionError, BizException,Exception {
				PageInfo pageInfo = new PageInfo();
				if(pageIndex == 0){
					isPage = 0;
				}else{
					isPage ++;
				}
				pageInfo.begin = pageIndex * pageSize + isPage;
				pageInfo.end = (pageIndex + 1) * pageSize + isPage;
//				Log.e("TAG", "pageInfo.begin: = " + pageInfo.begin + " , pageInfo.end: = " + pageInfo.end);
				return ServiceHelper.getInstance().postData(
						ServiceHost.getTaskListURL(),
						new Gson().toJson(pageInfo), TaskListInfo.class);
			}

			@Override
			protected void runWithResult(TaskListInfo result) throws Exception {
				if (result != null && result.getTasks() != null) {
					datasource = result;
					Log.e("TAG", "renwu: = " + new Gson().toJson(datasource));
					for (TaskInfo info : datasource.getTasks()) {
						try{
							tsql.deleteAttribute(info.getId());
						}catch (Exception e) {
						}
						tsql.addAttribute(info);
					}
					
					if (datasource != null && datasource.getTasks() != null) {
						List<TaskInfo> l = new ArrayList<TaskInfo>();
						for (TaskInfo ti : datasource.getTasks()) {
							int k = tnsql.getTaskList(ti.getId());
							// Log.e("k", String.valueOf(k));
							ti.setTemplateNum(ti.getTemplateNum() - k);
							if (ti.getTemplateNum() <= 0) {
								l.add(ti);
							}
						}
						datasource.getTasks().removeAll(l);
					}
					bindData();
				}
				asyntaskIsFinished = true;
				// TaskForAllActivity.hideLoading();
				hideLoading();
				finishedLoad(TAG);
			}

			@Override
			protected void runWithError(TaskListInfo result, int iErrorCode)
					throws Exception {
				asyntaskIsFinished = true;
				finishedLoad(TAG);
				isFromSql = false;
				try {
					tsql.delete();
				} catch (Exception e) {
				}
				hideLoading();
				getDataByUrl2();
			}
		}.execute();
	}

	private void getDataByUrl2() {

		registerLoadStatus(TAG);
		new ServiceAsynTask<TaskListInfo>() {

			@Override
			protected TaskListInfo callService() throws IOException,
					JsonParseException, AssertionError, BizException, Exception {
				if (pageIndex == 0) {
					isPage = 0;
				} else {
					isPage++;
				}
				PageInfo pageInfo = new PageInfo();
				pageInfo.begin = pageIndex * pageSize + isPage;
				pageInfo.end = (pageIndex + 1) * pageSize + isPage;
				return ServiceHelper.getInstance().postData(
						ServiceHost.getTaskListURL(),
						new Gson().toJson(pageInfo), TaskListInfo.class);
			}

			@Override
			protected void runWithResult(TaskListInfo result) throws Exception {
				if (result != null && result.getTasks() != null) {
					datasource = result;
					for (TaskInfo info : datasource.getTasks()) {
						try{
							tsql.deleteAttribute(info.getId());
						}catch (Exception e) {
						}
						tsql.addAttribute(info);
					}
					
					if (datasource != null && datasource.getTasks() != null) {
						List<TaskInfo> l = new ArrayList<TaskInfo>();
						for (TaskInfo ti : datasource.getTasks()) {
							int k = tnsql.getTaskList(ti.getId());
							// Log.e("k", String.valueOf(k));
							ti.setTemplateNum(ti.getTemplateNum() - k);
							if (ti.getTemplateNum() <= 0) {
								l.add(ti);
							}
						}
						datasource.getTasks().removeAll(l);
					}
					bindData();
				}
				asyntaskIsFinished = true;
				// TaskForAllActivity.hideLoading();
				hideLoading();
				finishedLoad(TAG);
			}

			@Override
			protected void runWithError(TaskListInfo result, int iErrorCode)
					throws Exception {
				if(PrefsUtils.getURL().equals(StringUtil.URL1)){
					PrefsUtils.setURL(StringUtil.URL2);
				}else if(PrefsUtils.getURL().equals(StringUtil.URL2)){
					PrefsUtils.setURL(StringUtil.URL1);
				}
				asyntaskIsFinished = true;
				finishedLoad(TAG);
				isFromSql = false;
				try {
					tsql.delete();
				} catch (Exception e) {
				}
				hideLoading();
			}
		}.execute();
	}

	private void bindData() {
//		Log.e("TAG", "size: = " + datasource.getTasks().size());
		if (adapter == null || pageIndex == 0) {
			adapter = new TaskListAdapter(datasource);
			adapter.setDelegate(this);
			adapter.setHandler(this);
			listView.setAdapter(adapter);
		} else {
			if (pageIndex >= 1) {
				adapter.appendDataSource(datasource);
				adapter.notifyDataSetChanged();
			}
		}
		if(isFromSql){
			totalRow = tsql.getTaskListCount();
		}else{
			totalRow = datasource.getRows();
		}
		if (totalRow > (pageIndex + 1) * pageSize) {
			isNeedLoading = true;
		} else {
			isNeedLoading = false;
		}
	}

	@Override
	public void onLoadingRowShowing(LoadingAdapter adapter) {
		if (pageIndex * pageSize < totalRow) {
			if (asyntaskIsFinished) {
				pageIndex++;
				if(isFromSql){
					getDataFromSql();
				}else{
					getData();
				}
				asyntaskIsFinished = false;
			}
		}
	}

	@Override
	public boolean needLoading() {
		return isNeedLoading;
	}

 

	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.btn_refresh) {
			if (asyntaskIsFinished) {
				showLoading();
				getData();
				asyntaskIsFinished = false;
			}
		} else if (v.getId() == R.id.btn_history) {
			finish();
		}
	}


	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
			DialogUtil.getExitAppDialog(this).show();
			return false;
		}
		return super.onKeyDown(keyCode, event);
	}
}
